
<template>
  <div>
      <Row :gutter="5">
          <Col :span="6">
            <Card >
                <div slot="title" class="orgSearch">
                    <Input  type="text" v-model="search_key" placeholder="客户/机构名称"></Input>
                    <Button type="primary" class="zh-hollow" @click="getTree(search_key)" >搜索</Button>
                </div>
                <div style="overflowX:auto">
                    <Tree v-for="(item,index) in data" :key="index"  :data="item" @on-select-change="selectChange"></Tree> 
                </div>
                    
            </Card>
          </Col>
          <Col :span="18">
            <Card>
                <div slot="title" v-if="readonly">
                        <Button @click="modal_newAdd=true" v-if="btnp.jggli_xzxjjg&&selectedType!=='customer'" type="primary" class="zh-hollow"  icon="plus-round">新增下级机构</Button>
                        <Button @click="modal_newAddNode=true" v-if="btnp.jggli_xzxnjd&&selectedType!=='customer'" type="primary" class="zh-hollow" icon="plus-round" style="margin-left:10px;">新增虚拟节点</Button>
                        <Button @click="handleAddNewPart" v-if="btnp.jggli_xzxsbm&&selectedType==='entity'" type="primary" class="zh-hollow" icon="plus-round" style="margin-left:10px;" >新增下属部门</Button>
                        <Button @click="modal_batch=true;" v-if="btnp.jggli_pldrjg&&selectedType!=='customer'" class="zh-hollow" type="warning" style="margin-left:10px;">批量导入机构</Button>
                </div>
                <div class="orgcontainer">
                    <p v-if="selectedType==='customer'">未选中机构</p>
                    <Tabs v-if="selectedType==='entity'" type="card" v-model="tabName">
                        <TabPane label="机构信息" name='name1'>
                            <Form :model="nodeDetail" :label-width="80">
                                <FormItem :label="readonly?'机构名称：':'机构名称*：'">
                                    <p v-if="readonly">{{nodeDetail.name}}</p>
                                    <Input v-else v-model="nodeDetail.name"></Input>
                                </FormItem>
                                <FormItem :label="readonly?'机构编码：':'机构编码*：'" >
                                    <p v-if="readonly">{{nodeDetail.number}}</p>
                                    <Input v-else v-model="nodeDetail.number" :maxlength="8"></Input>
                                </FormItem>
                                <FormItem label="新增时间："  >
                                    <p v-if="readonly">{{nodeDetail.time}}</p>
                                    <Input v-else readonly v-model="nodeDetail.time"></Input>
                                </FormItem>
                                <FormItem label="备注：">
                                    <p v-if="readonly">{{nodeDetail.remarks}}</p>                                                   
                                    <Input v-else :maxlength="20" v-model="nodeDetail.remarks" ></Input>               
                                </FormItem>
                                <FormItem :label="readonly?'所在地：':'所在地*：'">
                                    <p v-if="readonly">{{nodeDetail.locationS}}</p>
                                    <Cascader v-else v-model="nodeDetail.location" placeholder="请选择省市区" :data="areasData" ></Cascader>
                                </FormItem>
                                <FormItem :label="readonly?'详细地址：':'详细地址*：'">
                                    <p v-if="readonly">{{nodeDetail.address}}</p>
                                    <input v-else id="zhMapInput" class="ivu-input" type="text"  >
                                    <!-- <Input id="zhMapInput" v-else  v-model="nodeDetail.address" ></Input> -->
                                </FormItem>
                                <FormItem label="地图：">
                                    <div id="zhMap" style="height:300px"></div>
                                </FormItem>    
                                <div  class="zh-flex zh-flex-5">
                                    <template v-if="readonly">
                                        <Button v-if="btnp.jggli_bj" @click="readonly=false"  type="primary" class="zh-hollow"  icon="edit">编辑</Button>
                                        <Button v-if="btnp.jggli_ty" @click="stopNode" type="dashed" class="zh-hollow"  icon="android-hand">{{state=='0'?'恢复':'停用'}}</Button>
                                        <Button v-if="btnp.jggli_sz" @click="getAssOptions" type="info" class="zh-hollow"  icon="gear-a">设置</Button>
                                        <Button v-if="btnp.jggli_sc" @click="removeNode" type="error" class="zh-hollow"  icon="trash-b">删除</Button>
                                    </template>
                                    <template v-else class="zh-flex zh-flex-1">
                                        <Button @click="giveUp" type="ghost">放弃操作</Button>                                                   
                                        <Button @click="handleClickEditSave" style="marginLeft:25px;" type="primary" class="zh-hollow">保存</Button>                                                        
                                    </template>
                                </div>                                                                                                                                                            
                            </Form>    
                        </TabPane>
                        <TabPane label="下属部门" name='name2'>
                            <Table  border :columns="columns" :data="tableData" no-data-text="没有下属部门"></Table>
                            <!-- <Page :total="total" show-total show-sizer></Page> -->
                        </TabPane>
                    </Tabs>
                    <Tabs v-if="selectedType==='fictitious'" type="card">
                        <TabPane label="虚拟节点信息">
                            <Form :model="nodeDetail" :label-width="80">
                                <FormItem label="机构名称：">
                                    <p v-if="readonly">{{nodeDetail.name}}</p>
                                    <Input v-else v-model="nodeDetail.name"></Input>
                                </FormItem>
                                <FormItem label="新增时间：">
                                    <p v-if="readonly">{{nodeDetail.time}}</p>
                                    <Input v-else readonly v-model="nodeDetail.time"></Input>
                                </FormItem>
                                <FormItem label="备注：">
                                    <p v-if="readonly">{{nodeDetail.remarks}}</p>                                                   
                                    <Input v-else type="textarea" :maxlength="20" v-model="nodeDetail.remarks" ></Input>               
                                </FormItem>
                                <div class="zh-flex zh-flex-2">
                                    <template v-if="readonly" >
                                        <Button v-if="btnp.jggli_bj" @click="readonly=false"  type="primary" class="zh-hollow"  icon="edit">编辑</Button>
                                        <Button v-if="btnp.jggli_sc" @click="removeXnNode" type="error" style="marginLeft:25px;" class="zh-hollow"  icon="trash-b">删除</Button>
                                    </template>
                                    <template v-else >
                                        <Button @click="giveUp" type="ghost">放弃操作</Button>                                                   
                                        <Button @click="handleClickEditSave" style="marginLeft:25px;" type="primary" class="zh-hollow">保存</Button>                                                        
                                    </template>
                                </div>
                            </Form>
                        </TabPane>
                    </Tabs>
                </div>
            </Card>
          </Col>
      </Row>
      <Modal v-model="modal_batch" title="批量导入机构"  class-name="vertical-center-modal">
          <div style="padding:15px 30px;">
              <p>从本地选择Excel格式的机构列表，批量导入机构。</p>
              <Button type="text" style="color:#2d8cf0" > <a :href="url_InstTemp" target="_blank">下载Excel模板</a> </Button>
          </div>
          <div slot="footer" class="zh-flex zh-flex-5" style="width:100%;">
                <Button @clcik="modal_batch=false;" type="ghost">放弃操作</Button>
               <Upload 
                    ref="upload"
                    :with-credentials="true"
                    
                    :on-success="handleSuccess"
                    :on-progress="handleProgress"
                    :format="['xlsx','xls']"
                    :on-format-error="handleFormatError"
                    :before-upload="handleBeforeUpload"
                    :action="dr_url_inst">
                    <Button type="primary" :loading="btnloading" class="zh-hollow">选择文件</Button>
                </Upload>
          </div>
      </Modal>
      <Modal v-model="modal_newAdd" title="新增下级机构" :loading="addInst_loading" @on-ok="handleClickAddSave(0)" ok-text="保存" cancel-text="放弃操作" :mask-closable="false">
            <Form :model="addNewForm" :label-width="80" style="padding:15px 30px;">
                <FormItem label="上级机构">
                    <Input readonly v-model="addNewForm.superior" ></Input>
                </FormItem>
                <FormItem label="机构名称">
                    <Input  v-model="addNewForm.name" ></Input>
                </FormItem>
                <FormItem label="机构编码">
                    <Input  v-model="addNewForm.code" :maxlength="8" placeholder="长度为8 的数字和字母组成"></Input>
                </FormItem>
                <FormItem label="备注">
                    <Input type="textarea" :maxlength="20" v-model="addNewForm.remarks" ></Input>
                </FormItem>
                <FormItem label="所在地">
                    <Cascader change-on-select v-model="addNewForm.location" placeholder="请选择省市区" :data="areasData" ></Cascader>
                </FormItem>
                <FormItem label="详细地址">
                    <input id="sMapInput" class="ivu-input" type="text"  >
                    <!-- <Input id="sMapInput"  v-model="addNewForm.address"   :maxlength="20"></Input> -->
                </FormItem>
                <FormItem label="地图">
                        <div  id="sMap" style="height:200px"></div>    
                </FormItem>
            </Form>
      </Modal>
      <Modal v-model="modal_newAddNode" title="新增下级虚拟节点" :loading='addInst_loading' @on-ok="handleClickAddSave(1)" ok-text="保存" cancel-text="放弃操作" :mask-closable="false">
            <Form :model="addNewForm" :label-width="80" style="padding:15px 30px;">
                <FormItem label="上级机构">
                    <Input readonly v-model="addNewForm.superior" ></Input>
                </FormItem>
                <FormItem label="节点名称">
                    <Input  v-model="addNewForm.name" ></Input>
                </FormItem>
            </Form>     
      </Modal>
      <Modal v-model="modal_newAddPart" :title="addPartTitle" :loading='addPartLoading' @on-ok='savePart' ok-text="保存" cancel-text="放弃操作" :mask-closable="false">
            <Form :model="addNewPart" :label-width="60" style="padding:15px 30px;">
                <FormItem label="所属机构">
                    <Input readonly v-model="addNewPart.superior" ></Input>
                </FormItem>
                <FormItem label="部门名称">
                    <Input  v-model="addNewPart.name" ></Input>
                </FormItem>
                <FormItem label="所在地">
                    <Cascader change-on-select v-model="addNewPart.location" placeholder="请选择省市区" :data="areasData" ></Cascader>
                </FormItem>
                <FormItem label="详细地址">
                    <Input  v-model="addNewPart.address" ></Input>
                </FormItem>
            </Form>     
      </Modal>
      <Modal :loading='setLoading' v-model="modal_setNode" title="机构设置" @on-ok="saveSet"  ok-text="保存" cancel-text="放弃操作" :mask-closable="false">
          <Form :label-width="100" style="padding:15px 30px;">
                <FormItem label="派单方式">
                    <Select v-model="dispatch" >
                        <Option  v-for="item in dispatchList" :value="item.state" :key="item.state">{{ item.desc }}</Option>
                    </Select>                  
                </FormItem>
                <FormItem v-if='dispatch==1' label="关联运维人员">
                    <Select v-model="pro" >
                        <Option  v-for="item in proList" :value="item.uuid" :key="item.state">{{ item.name }}</Option>
                    </Select> 
                </FormItem>
          </Form>
      </Modal>
      <div id="searchResultPanel" style="display:none"></div>
  </div>
</template>

<script>
import {url_InstTemp,dr_url_inst} from '@/libs/downLoadUrl'
import util from '@/libs/util.js'
import {getOrgTreeData,getLeafInfo,getLeafPartInfo,getAss} from '@/libs/get.js'
import {saveInstInfo,stopInst,setAss,deleteInstMan,deleteInstPart} from '@/libs/post.js'
export default {
    name:'',
    data () {
        return {
            btnloading:false,
            dr_url_inst:dr_url_inst,
            url_InstTemp:url_InstTemp,
            btnp:{},
            btn:{
                jggli_xzxjjg:false,
                jggli_xzxnjd:false,
                jggli_pldrjg:false,
                jggli_xzxsbm:false,
                jggli_bj:false,
                jggli_ty:false,
                jggli_sz:false,
                jggli_sc:false
            },
            addPartLoading:true,
            setLoading:true,
            state:'',
            clickSave:true,
            addInst_loading:true,
            tabName:'name1',
            uuid:'',
            instUuid:'',
            dispatch:'',
            pro:'',
            proList:[],
            dispatchList:[],
            modal_setNode:false,
            readonly:true,
            modal_newAddPart:false,
            modal_newAddNode:false,
            modal_newAdd:false,
            addPartTitle:'',
            addNewPart:{
                superior:'',
                name:'',
                location:[],
                address:'',
                uuid:''
            },
            addNewForm:{
                superior:'',
                name:'',
                code:'',
                remarks:'',
                location:[],
                address:'',
                lon:'',
                lat:''
            },
            modal_batch:false,
            nodeValue:'',
            nodeDetail:{
                name:'',
                number:'',
                time:'',
                remarks:'',
                locationS:'',
                location:[],
                address:'',
                lon:'',
                lat:'',
            },
            instType:'',
            selectedType:'customer',//customer,entity,fictitious
            search_key:'',
            data:[],
            total:4,
            columns:[
                {
                    key:'name',
                    title:'部门名称'
                },{
                    key:'created',
                    title:'新增时间'
                },{
                    key:'action',
                    title:'操作',
                    align:'center',
                    render:(h,params)=>{
                        return h('div',[
                            h('Button',{
                                props:{
                                type:'text',
                                size:'small'
                                },
                                style:{
                                color:'#2D8CF0'
                                },
                                on:{
                                    click:()=>{
                                        this.handleEditNewPart(params.row)
                                    }
                                }
                            },'编辑'),
                            h('Button',{
                                props:{
                                type:'text',
                                size:'small'
                                },
                                style:{
                                color:'#EA0000'
                                },
                                on:{
                                    click:()=>{
                                      this.removePart(params.row.uuid);
                                    }
                                }
                            },'删除'),
                        ])
                    }
                }
            ],
            tableData:[],
            areasData:this.$store.state.user.areaData,
        };
    },
    methods:{
        handleSuccess(res, file){
            if(res.code==200){
                this.$Notice.success({
                    desc:res.msg
                });
                this.modal_batch=false;
                this.getTree(this.search_key);
            }else{
                this.$Notice.error({
                    desc:res.msg
                })
            }
            this.btnloading=false;
        },
        handleProgress(){
            this.btnloading=true;
        },
        handleBeforeUpload(){

        },
        handleFormatError (file) {
            this.$Notice.warning({
                title: '文件格式错误',
                desc: '请选择 xlsx 或 xls 格式的文件'
            });
        },
        async deletePart(uuid){
            let res=await deleteInstPart({uuid});
            let response=res.data;
            if(response.code===200){
                this.$Notice.success({
                    desc:'已删除'
                });
               this.getLeafPart();
            }else{
                this.$Notice.error({
                
                desc:response.msg
                });
            }
        },
        async deleteInst(){
            let uuid=this.uuid;
            let res=await deleteInstMan({uuid});
            let response=res.data;
            if(response.code===200){
                this.$Notice.success({
                    desc:'已删除'
                });
                this.uuid='';
                this.instType='';
                this.state='';
                this.addNewForm.superior='';
                this.getTree();
            }else{
                this.$Notice.error({
                
                desc:response.msg
                });
            }
        },
        async saveSet(){
            let uuid=this.uuid;
            let assign_mode=this.dispatch;
            let assign_to=this.pro;
            if(assign_mode==''){
                this.$Notice.error({
                    desc:'请选择派单方式'
                })
            }
            else if(assign_mode=='1'&&!assign_to){
                this.$Notice.error({
                    desc:'请选择关联的运维人员'
                })
            }else{
                let res=await setAss({uuid,assign_mode,assign_to});
                let response=res.data;
                if(response.code===200){
                    this.$Notice.success({
                        desc:'已设置'
                    });
                    this.modal_setNode=false;
                }else{
                    this.$Notice.error({
                    desc:response.msg
                    });
                }
            }
            
            this.setLoading=false;
            let that=this;
            setTimeout(()=>{
                that.setLoading=true;
            },500)
        },
        async getAssOptions(){
            let uuid=this.uuid;
            let city=this.nodeDetail.location[1];
            let res=await getAss(uuid,city);
            let response=res.data;
            if(response.code===200){
                this.dispatchList=response.data.AssignMode;
                this.proList=response.data.AssignTo;
                this.dispatch=response.data.inst.assign_mode;
                this.pro=!!response.data.inst.assign_to?response.data.inst.assign_to:'';
                this.modal_setNode=true;
            }else{
                this.$Notice.error({
                
                desc:response.msg
                });
                return false
            }
        },
        async stopUse(){
            let uuid=this.uuid;
            let state=1-this.state;
            let res=await stopInst({uuid,state});
            let response=res.data;
            if(response.code===200){
                this.$Notice.success({
                    desc:state==1?'已恢复':'已停用'
                });
                this.getTree(this.search_key);
                this.getLeaf();

            }else{
                this.$Notice.error({
                
                desc:response.msg
                });
                return false
            }
        },
        autoMap(id,inputId,obj){
            let that=this;
            let map = new BMap.Map(id);
            map.enableScrollWheelZoom(true);
            let point; 
            if(!!obj.lat){
                point=new BMap.Point(obj.lon,obj.lat);
            }else{
                point=new BMap.Point(120.187159,30.194212);
            }
            map.centerAndZoom(point, 18);  // 初始化地图，设置中心点坐标和地图级别
            let marker = new BMap.Marker(point); // 创建标注 
            map.addOverlay(marker);
            let label = new BMap.Label(`${point.lng}，${point.lat}`, { offset: new BMap.Size(20, -10) });
            marker.setLabel(label);
            marker.enableDragging();
            let geoc=new BMap.Geocoder();
            marker.addEventListener("dragend", function (e) {
                obj.lon=e.point.lng;
                obj.lat=e.point.lat;
                let label = new BMap.Label(`${obj.lon}，${obj.lat}`, { offset: new BMap.Size(20, -10) });
                marker.setLabel(label);
                geoc.getLocation(e.point,function(rs){
                    let addComp=rs.addressComponents;
                    let add=`${addComp.province} ${addComp.city} ${!!addComp.district?addComp.district:''} ${!!addComp.street?addComp.street:''} ${!!addComp.business?addComp.business:''}`;
                    obj.address=add;
                    ac.setInputValue(add)
                })
            });
            let ac=new BMap.Autocomplete({
                'input':inputId,
                'location':map
            });
            let myValue;
            ac.setInputValue(obj.address);
            ac.addEventListener("onhighlight", function (e) { //鼠标放在下拉列表上的事件
                let str = "";
                let _value = e.fromitem.value;
                let value = "";
                if (e.fromitem.index > -1) {
                    value = _value.province + _value.city + _value.district
                        + _value.street + _value.business;
                }
                str = "FromItem<br />index = " + e.fromitem.index
                    + "<br />value = " + value;

                value = "";
                if (e.toitem.index > -1) {
                    _value = e.toitem.value;
                    value = _value.province + _value.city + _value.district
                        + _value.street + _value.business;
                }
                str += "<br />ToItem<br />index = " + e.toitem.index
                    + "<br />value = " + value;
                document.getElementById("searchResultPanel").innerHTML = str;
            });
            ac.addEventListener('onconfirm',function(e){
                let _value=e.item.value;
                myValue=`${_value.province} ${_value.city} ${_value.district} ${_value.street} ${_value.business}`;
                obj.address=myValue;
                document.getElementById("searchResultPanel").innerHTML = "onconfirm<br />index = "
                + e.item.index + "<br />myValue = " + myValue;
                function myFun(val){
                    if(val.getNumPois()==0){
                        that.$Notice.info({
                            desc:'没有搜索到，请手动设置'
                        })
                    }else{
                        let pp=val.getPoi(0).point;
                        // let pp=local.getResults().getPoi(0).point;
                        obj.lon=pp.lng;
                        obj.lat=pp.lat;
                        map.centerAndZoom(pp,18);
                        let marker = new BMap.Marker(pp); // 创建标注 
                        map.addOverlay(marker);
                        marker.enableDragging();
                        marker.addEventListener("dragend", function (e) {
                            obj.lon=e.point.lng;
                            obj.lat=e.point.lat;
                            geoc.getLocation(e.point,function(rs){
                                let addComp=rs.addressComponents;
                                let add=`${addComp.province} ${addComp.city} ${!!addComp.district?addComp.district:''} ${!!addComp.street?addComp.street:''} ${!!addComp.business?addComp.business:''}`;
                                obj.address=add;
                                ac.setInputValue(add)
                            })
                        });
                    }
                    
                }
                map.clearOverlays();
                let local=new BMap.LocalSearch(map,{
                    onSearchComplete:myFun
                });
                local.search(myValue);
            });
        },
        selectMap(id,obj){
            let map = new BMap.Map(id);
            let point; 
            if(!!obj.lat){
                point=new BMap.Point(obj.lon,obj.lat);
            }else{
                point=new BMap.Point(120.187159,30.194212);
            }
            map.centerAndZoom(point, 15);  // 初始化地图，设置中心点坐标和地图级别
            map.addControl(new BMap.NavigationControl());
            let marker = new BMap.Marker(point); // 创建标注 
            map.addOverlay(marker);
            marker.enableDragging();
            marker.addEventListener("dragend", function (e) {
                obj.lon=e.point.lng;
                obj.lat=e.point.lat;
            });
        },
        async selectChange(e){
            if(e.length>0){
                this.addNewForm.superior=e[0].name;
                this.readonly=true;
                this.tabName='name1';
                this.uuid=e[0].uuid;
                this.data=this.data.map(item=>{
                    item=this.judgeSelected(item,this.uuid);
                    return item
                })
                this.instType=e[0].inst_type;
                this.dr_url_inst=dr_url_inst+'&selectedInstuuid='+e[0].uuid;
                await this.getLeaf();
                
                if(this.instType=='0'){
                    await this.getLeafPart();
                }
            }else{
                this.uuid='';
                this.instType='';
                this.state='';
                this.addNewForm.superior='';
            }
            
            
        },
        async getLeafPart(){
            let res=await getLeafPartInfo(this.uuid);
            let response=res.data;
            if(response.code===200){
               this.tableData=response.data.rows;
               
               
            }else{
                this.$Notice.error({
                    title: '请求出错',
                    desc:response.msg
                });
                
            }
        },
        async getLeaf(){
            let res=await getLeafInfo(this.uuid);
            let response=res.data;
            if(response.code===200){
                this.state=response.data.state;
               this.nodeDetail={
                    name:response.data.name,
                    number:response.data.code,
                    time:response.data.created.slice(0,16),
                    remarks:response.data.remark,
                    locationS:!!response.data.province?`${response.data.province} ${response.data.city} ${!!response.data.district?response.data.district:''}`:'',
                    location:!!response.data.province?[response.data.province,response.data.city,!!response.data.district?response.data.district:'']:[],
                    address:response.data.addr,
                    lon:response.data.longitude,
                    lat:response.data.latitude
               };
               if(!!this.nodeDetail.lon){
                   document.getElementById('zhMap').style.display='block';
                   util.initMap('zhMap',this.nodeDetail.lon,this.nodeDetail.lat)
               }else{
                   document.getElementById('zhMap').style.display='none';
               }
               
            }else{
                this.$Notice.error({
                    title: '请求出错',
                    desc:response.msg
                });
                
            }
        },
        judgeSelected(arr,uuid){
            let nArr = arr.map(item => {
                if (item.uuid == uuid) {
                    item.selected = true;
                }else{
                    item.selected = false;
                }
                if (!!item.children && item.children.length > 0) {
                    item.children = util.TreeFormat(item.children)
                }
                return item
            })
            return nArr
        },
        async getTree(name){
            let res=await getOrgTreeData(name);
            let response=res.data;
            if(response.code===200){
                this.data=util.TreeFormat(response.data,this.uuid).map(item=>{
                    return [item]
                });
            }else{
                this.$Notice.error({
                title: '请求出错',
                desc:response.msg
                });
                
            }
        },
        async savePart(){
            if(!this.addNewPart.name){
                this.$Notice.error({
                    desc:'请输入部门名称'
                })
            }else if(!this.addNewPart.location[0]){
                this.$Notice.error({
                    desc:'请选择所在地'
                })
            }else if(!this.addNewPart.address){
                this.$Notice.error({
                    desc:'请输入详细地址'
                })
            }else{
                let parent_uuid=this.uuid;
                let name=this.addNewPart.name;
                let code='';
                let remark='';
                let addr=this.addNewPart.address;
                let province=this.addNewPart.location[0];
                let city=this.addNewPart.location[1];
                let district=this.addNewPart.location[2];
                let longitude='';
                let latitude='';
                let uuid=this.addNewPart.uuid;
                let flag=this.addPartTitle==='新增下属部门'?'save':'edit';
                let node_type=1;
                let inst_type='';
                let res=await saveInstInfo({inst_type,parent_uuid,name,code,remark,province,city,district,addr,longitude,latitude,uuid,flag,node_type});
                let response=res.data;
                if(response.code===200){
                    this.$Notice.success({
                        desc:'保存成功'
                    })
                    this.modal_newAddPart=false;
                    this.getLeafPart(this.uuid);
                }else{
                    this.$Notice.error({
                        desc:response.msg
                    });
                }
            }
            
            this.addPartLoading=false;
            let that=this;
            setTimeout(()=>{
                that.addPartLoading=true;
            },500)
        },
        async addSave(inst_type){
            let parent_uuid=this.uuid;
            let name=this.addNewForm.name;
            let code=this.addNewForm.code;
            let remark=this.addNewForm.remarks;
            let addr=this.addNewForm.address;
            let province=this.addNewForm.location[0];
            let city=this.addNewForm.location[1];
            let district=this.addNewForm.location[2];
            let longitude=this.addNewForm.lon;
            let latitude=this.addNewForm.lat;
            let uuid='';
            let flag='save';
            let node_type=0;
            let res=await saveInstInfo({inst_type,parent_uuid,name,code,remark,province,city,district,addr,longitude,latitude,uuid,flag,node_type});
            let response=res.data;
            if(response.code===200){
                this.$Notice.success({
                    desc:'保存成功'
                })
                if(inst_type=='0'){
                    this.modal_newAdd=false
                }else{
                    this.modal_newAddNode=false;
                }
                this.getTree(this.search_key);
            }else{
                this.$Notice.error({
                    desc:response.msg
                });
                
            }
        },
        async handleClickAddSave(inst_type){
            if(!this.addNewForm.name){
                this.$Notice.error({
                    desc:'请输入机构名称'
                })
            }else if(this.inst_type=='0'){
                const reg=/^[0-9A-Za-z]{8}$/;
                if(this.addNewForm.code.length>0&!reg.test(this.addNewForm.code)){
                    this.$Notice.error({
                        desc:'机构编码格式错误'
                    })
                }else if(this.addNewForm.location.length<=0||!this.addNewForm.location[0]){
                    this.$Notice.error({
                        desc:'请选择所在地'
                    })
                }else if(!this.addNewForm.address){
                    this.$Notice.error({
                        desc:'请输入详细地址'
                    })
                }else{
                    //保存
                    await this.addSave(inst_type);
                }
            }else{
                //保存
                await this.addSave(inst_type);
            }
            this.addInst_loading=false;
            let that=this;
            setTimeout(()=>{
                that.addInst_loading=true;
            },500)
              
        },
        async giveUp(){
            this.readonly=true;
            await this.getLeaf();
        },
        async editSave(){
            let inst_type=this.instType;
            let name=this.nodeDetail.name;
            let parent_uuid='';
            let code=this.nodeDetail.number;
            let remark=this.nodeDetail.remarks;
            let province=this.nodeDetail.location[0];
            let city=this.nodeDetail.location[1];
            let district=this.nodeDetail.location[2];
            let addr=this.nodeDetail.address;
            let longitude=this.nodeDetail.lon;
            let latitude=this.nodeDetail.lat;
            let uuid=this.uuid;
            let flag='edit';
            let node_type=0;
            let res=await saveInstInfo({inst_type,parent_uuid,name,code,remark,province,city,district,addr,longitude,latitude,uuid,flag,node_type});
            let response=res.data;
            if(response.code===200){
                this.$Notice.success({
                    desc:'保存成功'
                })
                this.readonly=true;
                this.getLeaf();
                this.getTree(this.search_key);
                
            }else{
                this.$Notice.error({
                    desc:response.msg
                });
                
            }
        },
        async handleClickEditSave(){
            if(this.clickSave){
                this.clickSave=false;
                if(!this.nodeDetail.name){
                    this.$Notice.error({
                        desc:'请输入机构名称'
                    })
                }else if(this.selectedType=='entity'){
                    const reg=/^[0-9A-Za-z]{8}$/;
                    console.log(this.nodeDetail.number);
                    console.log(reg.test(this.nodeDetail.number))
                    if(!this.nodeDetail.number){
                        this.$Notice.error({
                            desc:'请输入机构编码'
                        })
                    }else if(!reg.test(this.nodeDetail.number)){
                        this.$Notice.error({
                            desc:'机构编码格式错误'
                        })
                    }else if(this.nodeDetail.location.length<=0||!this.nodeDetail.location[0]){
                        this.$Notice.error({
                            desc:'请选择所在地'
                        })
                    }else if(!this.nodeDetail.address){
                        this.$Notice.error({
                            desc:'请输入详细地址'
                        })
                    }else{
                        //保存
                        this.editSave();
                    }
                }else{
                    //保存
                    this.editSave();
                }
            
                this.clickSave=true;
            }
            
        },
        handleAddNewPart(){
            this.addPartTitle="新增下属部门";
            this.modal_newAddPart=true;
             this.addNewPart.superior=this.addNewForm.superior;
        },
        handleEditNewPart(obj){
            this.addPartTitle="编辑下属部门";
            
            this.addNewPart={
                    superior:this.addNewForm.superior,
                    name:obj.name,
                    location:[obj.province,obj.city,obj.district],
                    address:obj.addr,
                    uuid:obj.uuid
                };
            this.modal_newAddPart=true;

        },
        removePart(uuid){
            let config={
                title:'删除部门',
                content:'删除部门后，部门下的人员和设备直接归属到机构下。删除部门不可恢复。',
                okText:'删除',
                cancelText:'放弃操作',
                onOk:()=>{
                    this.deletePart(uuid);
                }
            }
            this.$Modal.confirm(config)            
        },
        removeNode(){
            let config={
                title:'删除机构',
                content:'删除机构会同时删除该机构下的数据，删除不可恢复。',
                okText:'删除',
                cancelText:'放弃操作',
                onOk:()=>{
                  this.deleteInst()
                }
            }
            this.$Modal.confirm(config)
        },
        removeXnNode(){
            let config={
                title:'删除节点',
                content:'删除节点不可恢复。',
                okText:'删除',
                cancelText:'放弃操作',
                onOk:()=>{
                  this.deleteInst()
                }
            }
            this.$Modal.confirm(config)
        },
        stopNode(){
            let config
            if(this.state=='1'){
                config={
                    title:'停用机构',
                    content:'停用机构后，仍然能查询该机构的历史数据，但不能产生新的数据。停用的机构可以恢复正常。',
                    okText:'停用',
                    cancelText:'放弃操作',
                    onOk:()=>{
                    this.stopUse()
                    }
                }
            }else{
                config={
                    title:'恢复机构',
                    content:'恢复机构后，可产生新的数据。',
                    okText:'恢复',
                    cancelText:'放弃操作',
                    onOk:()=>{
                        this.stopUse()
                    }
                }
            }
            this.$Modal.confirm(config)
        },
        removeVirtualNode(){
            let config={
                title:'删除节点',
                content:'删除节点不可恢复。',
                okText:'删除',
                cancelText:'放弃操作',
                onOk:()=>{
                    
                }
            }
            this.$Modal.confirm(config)
        }
    },
    watch:{
        instType:function(){
            this.selectedType=this.instType=='1'?'fictitious':this.instType=='0'?'entity':'customer';
        },
        readonly:function(){
            if(!this.readonly&&this.instType=='0'){
                //this.selectMap('zhMap',this.nodeDetail)
                let that=this;
                document.getElementById('zhMap').style.display='block';
                setTimeout(()=>{
                    that.autoMap('zhMap','zhMapInput',that.nodeDetail);
                },500)
            }else if(this.readonly&&!this.nodeDetail.lon){
                document.getElementById('zhMap').style.display='none';
            }
        },
        modal_newAdd:function(){
            if(this.modal_newAdd){
                    //this.selectMap('sMap',this.addNewForm);
                    let that=this;
                    setTimeout(()=>{
                        that.autoMap('sMap','sMapInput',that.addNewForm);
                    },500)
                    
            }else{
                let fa=this.addNewForm.superior;
                this.addNewForm={
                    superior:fa,
                    name:'',
                    code:'',
                    remarks:'',
                    location:[],
                    address:'',
                    lon:'',
                    lat:''
                }
            }
        },
        modal_newAddNode:function(){
            if(!this.modal_newAddNode){
                let fa=this.addNewForm.superior;
                this.addNewForm={
                    superior:fa,
                    name:'',
                    code:'',
                    remarks:'',
                    location:[],
                    address:'',
                    lon:'',
                    lat:''
                }
            }
        },
        modal_newAddPart:function(){
            if(!this.modal_newAddPart){
                this.addNewPart={
                    superior:this.addNewForm.superior,
                    name:'',
                    location:[],
                    address:'',
                    uuid:''
                }
            }
        }
    },
    created(){
        let that=this;
        // setTimeout(()=>{
        //     that.areasData=that.$store.state.user.areaData;
        // },5000);
        this.getTree(this.search_key);
        this.btnp=util.bpower(this,this.btn);
    }

}

</script>
<style lang='scss' >
.tangram-suggestion-main {
    z-index: 9999999;
  }
.orgSearch{
    position:relative;
    padding-right:60px;
    .ivu-input{
        width:100%;
    }
    .ivu-btn{
        position:absolute;
        top:0;
        right:0;
    }
}

.orgcontainer{
    min-height:150px;
}
.ivu-upload-list{
    display:none!important;
}
</style>